package com.jun.junapiclient;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ApiClient
 * @Description
 * @Author junjun
 * @Date 2023/6/3 14:06
 * @Version V1.0
 */
public class ApiClient {
    private final String accessKey;
    private final String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }
    private Map<String, String> getHeaders(String body) throws UnsupportedEncodingException {
        Map<String, String> header = new HashMap<>();
        header.put("accessKey", accessKey);
        header.put("sign", SignUtil.getSign(body, secretKey));
        // 防止中文乱码
        header.put("body", URLEncoder.encode(body, StandardCharsets.UTF_8.name()));
        header.put("nonce", RandomUtil.randomNumbers(5));
        header.put("timestamp", String.valueOf(System.currentTimeMillis()));
        return header;
    }
    public String getNameByGet(String name) {
        return HttpUtil.get("http://localhost:8123/api/name/" + name);
    }

    public String getNameByPost(String name) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<String, Object>();
        stringObjectHashMap.put("name", name);
        return HttpUtil.post("http://localhost:8123/api/name", stringObjectHashMap);
    }

    public String getNameByPost(User user) throws UnsupportedEncodingException {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse execute = HttpRequest.post("http://localhost:8123/api/name/user").addHeaders(getHeaders(json)).body(json).execute();
        if (execute.isOk()) {
            return execute.body();
        }
        return "fail";
    }
}
